import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { loginAPI } from '@/apis/user'
import { useCartStore } from './cart'
import { mergeCartAPI } from '@/apis/cart'

export const useUserStore = defineStore('user', () => {

    const cartStore = useCartStore()
    // 定义用户基本数据
    const userInfo = ref({})

    // 判断token是否存在
    const isToken = computed(() =>{
        return userInfo.value.token ? true : false
    })
    // action方法
    const getUserInfo = async ({ account, password }) => {
        const res = await loginAPI({ account, password })
        userInfo.value = res.result
        // 合并购物车
        await mergeCartAPI(cartStore.cartList.map((item) => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count: item.count
            }
        }))
        // 渲染购物车
        cartStore.getCartList()

    }

    // 移除用户信息
    const removeInfo = () => {
        userInfo.value = {}
        // 清空本地购物车
        cartStore.clearCart()
    }

    // return 
    return {
        userInfo,
        isToken,
        getUserInfo,
        removeInfo
    }
}, {
    persist: true // 开启数据持久化
})